/**
 * 添加采购单modal
 */

'use strict';

var React = require('react-native');
var {msg} = require('iflux-native');
var fetch = require('../fetch');
var QMConst = require('../const');
var QMLoading = require('../loading');
var Button = require('./button');
var QMBtnContainer = require('../button');
var WIDTH = require('Dimensions').get('window').width;
var HEIGHT = require('Dimensions').get('window').height;
var ViewPager = require('react-native-viewpager');
var QMMktActivityDetail = require('../mkt-activity-detail');
var GoodsDetails = require('../goods-details');


var {
  StyleSheet,
  View,
  Text,
  Image,
  StatusBarIOS,
  InteractionManager,
  PixelRatio, 
  TouchableOpacity,
  TouchableHighlight,
  ScrollView,
  Navigator,
  Platform,
  ListView
} = React;


// just do nothing
var noop = () => {};

var dataSource = new ViewPager.DataSource({
  pageHasChanged: (p1, p2) => p1 !== p2,
});

var giftSource = new ListView.DataSource({
  rowHasChanged: (r1, r2) => r1 != r2
});

/**
 * 详情
 */
var ProductDetail = React.createClass({
  getDefaultProps(){
    return {
      /*商品id*/
      spuId: '',
      /*货品id*/
      skuId: '',
      onHide: noop,
      /*来源，现在就在值为shelf时有特殊操作*/
      source: ''
    }
  },


  getInitialState() {

    return {
      /*当前loading的状态*/
      isLoading: false,
      /*商品的缩略图*/
      img: '',
      /*商品名称*/
      name: '',
      /*商品编号*/
      bn: '',
      /*单位*/
      unit: '',
      specs: [],
      /*市场价*/
      mktPrice: null,
      /*区间价*/
      priceRange: null,
      /*是否收藏*/
      isShelf: false,
      /*一进来的是否收藏状态*/
      defaultIsShelf: false,
      /*默认选中商品详情*/
      selectBtn: 'detail',
      visible: false,

      animated: true,
      transparent: true,
      /*营销活动-满赠*/
      mktArray_1: [],
      /*营销活动-满折*/
      mktArray_2: [],
      /*营销活动-满减*/
      mktArray_3: [],
      /*详情图片*/
      mobileDetail: [],
      /*营销活动-满折-显示更多*/
      mktArray_2_show: false,
      /*营销活动-满减-显示更多*/
      mktArray_3_show: false,
      /* 营销活动-sku列表 */
      mkts: [],
      /*图片列表*/
      imgList: [],
      /*购物车商品数量*/
      cartCount: 0
    };
  },


  /**
   * 获取数据
   */
  componentDidMount() {
    InteractionManager.runAfterInteractions(() => {
      if(__DEV__) {
        console.log('等到所有的动画结束才去加载数据...');
      }
      fetch(`${QMConst.HOST}/goods/detail/${this.props.spuId}`)
        .then((res) => {
          if (__DEV__) {
            console.log('获取商品详情数据:', res);
          }

          this.setState({
            isLoading: true,
            unit: res.det.unit,
            img: res.det.img,
            bn: res.det.bn,
            name: res.det.name,
            mktPrice: res.det.mktpr,
            priceRange: res.det.pricereg,
            isShelf: res.det.isfav,
            defaultIsShelf: res.det.isfav,
            params: res.params,
            mktArray_1: res.marketingList1,
            mktArray_2: res.marketingList2,
            mktArray_3: res.marketingList3,
            giftItemList: res.giftItemList,
            mkts: res.mkts,
            imgList: res.det.imgList
          });

        });

        var url = `${QMConst.HOST}/goods/mobileDetail?productId=${this.props.spuId}`;
        fetch(url)
          .then((res) => {
            this.setState({mobileDetail: res});
          });

        // 刷新商品详情页购物车数量
        this._handleRefreshCount();
    });
  },


  /**
   * 还原StatusBar
   */
  componentWillUnmount(){
    if (Platform.OS === 'ios') {
      StatusBarIOS.setHidden(false);
    }
  },


  render() {
    return this._renderContent();
  },


  _renderContent() {

    return (
      <View style={styles.container}>
        {this.state.isLoading ? this._renderDetail() : <QMLoading/>}
        {/*关闭按钮*/}
        <QMBtnContainer
          style={styles.back}
          onPress={this._handleClose}>
          <Image
            source={require('img/left.png')}
            style={styles.backLeft}
          />
        </QMBtnContainer>
      </View>
    );
  },


  _renderDetail() {
    var discountSkuList = [];
    var cutSkuList = [];
    var giftList = [];
    if(this.state.mkts && this.state.mkts.length > 0){
      this.state.mkts.forEach((v, i) => {
        var mkt = v.mkt;
         if(mkt && mkt.length > 0){
           mkt.forEach((m, j) => {
             if(m == 1){
               giftList.push(v.name);
             }else if(m == 2){
               discountSkuList.push(v.name);
             } else if(m == 3){
               cutSkuList.push(v.name);
             }
           });
         }
      });
    };

    return (
      <View style={styles.wrap}>
      <ScrollView style={styles.scroll}>
        <View style={styles.container}>
          <View style={styles.pic}>
            {/*商品图片*/}
            <ViewPager
            style={styles.img}
            dataSource={dataSource.cloneWithPages(this.state.imgList)}
            renderPage={this._renderPage}
            isLoop={this.state.imgList.length > 1 ? true : false}
            autoPlay={this.state.imgList.length > 1 ? true : false}/>
          </View>
          <View style={styles.detail}>
            <View style={styles.detailMain}>
              {/*商品编号*/}
              <Text style={styles.grey}>{this.state.bn}</Text>
              {/*商品名称*/}
              <Text style={styles.proText} numberOfLines={2}>
                {this.state.name}
              </Text>
              {/*商品区间价格*/}
              <Text style={styles.priceText}>
                {this.state.priceRange && '￥' + this.state.priceRange}
              </Text>
            </View>
            {(this.state.mktArray_1.length > 0 || this.state.mktArray_2.length > 0 || this.state.mktArray_3.length > 0) ?
              <View style={styles.mktRow}>
                <View style={[styles.mktBody]}>
                  <Text style={[styles.text,styles.grey]}>优惠</Text>
                </View>
                <View style={{flex: 1}}>
                  <QMMktActivityDetail style={{flex: 1}} gifts={this.state.mktArray_1} discount={this.state.mktArray_2} cut={this.state.mktArray_3}
                    discountSkuList={discountSkuList} cutSkuList={cutSkuList} giftSkuList={giftList} isDrop={true}/>
                  {
                    this.state.giftItemList.length > 0 ?
                    <ListView
                      style={styles.gitsListView}
                      showsVerticalScrollIndicator={true}
                      automaticallyAdjustContentInsets={false}
                      renderRow={this._renderGitRow}
                      dataSource={giftSource.cloneWithRows(this.state.giftItemList)}/> : null
                  }
                </View>
              </View> : null
            }
          </View>

          {/*商品详情及属性参数*/}
          <View style={styles.infor}>
            <View style={styles.tab}>
              <View style={styles.tabBtn}>
                <TouchableHighlight
                  underlayColor={'#326da7'}
                  onPress={this._handleDetail}
                  style={[styles.tabButton,this.state.selectBtn == 'detail' && styles.tabButtonCur]}>
                  <Text style={[styles.txt,this.state.selectBtn == 'detail' && styles.txtCur]}>商品详情</Text>
                </TouchableHighlight>
                <TouchableHighlight
                  underlayColor={'#326da7'}
                  onPress={this._handleParams}
                  style={[styles.tabButton,this.state.selectBtn == 'params' && styles.tabButtonCur]}>
                  <Text style={[styles.txt,this.state.selectBtn == 'params' && styles.txtCur]}>属性参数</Text>
                </TouchableHighlight>
              </View>
            </View>

            <View>
              {this.state.selectBtn == 'detail'
                ?
                this._getMobileDetail()
                : <AttributeParams params={this.state.params}/>
              }
            </View>

          </View>

        </View>
      </ScrollView>
      <Button
        onPress={this._handlePress.bind(this, true)}
        onShelfPress={this._handleEditShelf}
        isShelf={this.state.isShelf}
        disabled={true}
        cartCount={this.state.cartCount}
        />
      </View>
    );
  },


  _renderGitRow(row, _, index){
    return (
      <View style={styles.detailOneLine}>
        <View style={styles.labelGift}>
          <Image style={styles.giftBg} source={require('img/gift.png')} />
          <Text style={styles.labelTxt}>赠品</Text>
        </View>
        <View style={[styles.flexGrow, styles.giftNameItem]}>
          <Text numberOfLines={1} style={[styles.flexGrow,styles.giftTxt]}> {row.name}</Text>
          <Text style={[styles.giftTxt,styles.grey]}>{'x' + row.count}</Text>
        </View>
      </View>
    );
  },


  /**
   * 渲染图片切换页面
   * @param data
   * @param pageID
   * @returns {XML}
   * @private
   */
  _renderPage: function(data,pageID){
    return (
      <Image
        source={{uri: data}}
        style={styles.img} />
    );
  },


  /**
   * 关闭
   */
  _handleClose() {
    // 如果是收藏状态发生变更，并且是通过收藏点进来的，就刷新dataList
    if(this.state.defaultIsShelf != this.state.isShelf && this.props.source == 'shelf') {
      msg.emit('dataList:refresh', 'goods/shelfList');
    }
    msg.emit('route:backToLast');
  },


  /**
   * 加入采购单
   * @param visible
   * @private
   */
  _handlePress() {

    var component = (
      <GoodsDetails
        skuId={this.props.skuId}
        spuId={this.props.spuId}
        source={this.props.source}
        />
    )
    msg.emit('app:pop-up', {component: component});
  },


  /**
   * 修改收藏
   * @private
   */
  _handleEditShelf(){
    var isShelf = this.state.isShelf;
    var productId = this.props.spuId;
    var goodsId = this.props.skuId;

    var url = `${QMConst.HOST}/goods/addShelf?productId=${productId}&goodsId=${goodsId}`;
    if(isShelf) {
      url = `${QMConst.HOST}/goods/delShelf?productId=${productId}`;
    }

    fetch(url)
      .then((res) => {
        this.setState({
          isShelf: !isShelf
        });
      })
  },

  /**
   * 图片详情
   * @private
   */
  _getMobileDetail() {
    return (
      <View style={styles.cont}>
        {
          this.state.mobileDetail.length > 0 ?
            this.state.mobileDetail.map((v) => {
              return (
                <Image style={styles.proImage} source={{uri: v}}/>
              )
            })
            : <Text style={styles.grey}>暂无商品详情</Text>
        }
      </View>
    )
  },


  /**
   * 显示商品详情
   */
  _handleDetail(){
    this.setState({
      selectBtn: 'detail'
    });
  },


  /**
   * 显示商品属性参数
   */
  _handleParams(){
    this.setState({
      selectBtn: 'params'
    });
  },


  /**
   * 刷新商品详情购物车数量
   */
  _handleRefreshCount(){
    fetch(`${QMConst.HOST}/cart/count`)
      .then((res) => this.setState({cartCount: res}));
  }
});


/**
 * 属性参数tab页
 */
var AttributeParams = React.createClass({
  render() {

    var params = this.props.params;

    var content = params && params.content || '';

    var paramType = params && params.paramType || 0;

    if(paramType == 0){
      return (
        <View style={styles.cont}>
          <Text style={styles.grey}>暂无属性参数</Text>
        </View>
      );
    }


    let tableElements = null;
    // paramType为零时content为字符串
    if (paramType == 0) {
      tableElements = content;
    }
    // paramType为1时content为数组
    else if (paramType == 1) {
      tableElements = content.map((v1, k1) => {
        let trElements = v1.paramList.map((v2, k2) => {
          return (
            <View style={styles.listRow} key={k2}>
              <Text style={styles.propertyName}>{v2.name}</Text>
              <Text style={styles.propertyTxt}>{v2.value}</Text>
            </View>
          )
        });

        return (
          <View style={styles.property} key={k1}>
            <View>
              <Text style={styles.propertyTitle}>基本参数</Text>
            </View>
            <View>
            {trElements}
            </View>
          </View>
        )
      });
    }

    if (paramType == 0) {
      return (
        <View>
          {tableElements}
        </View>
      );
    }
    else{
      return (
        <View>
          {tableElements}
        </View>
      );
    }
  }
});


var styles = StyleSheet.create({
  wrap: { flex: 1, },
  scroll: {
    height: HEIGHT-63,
  },
  container: {
    flex: 1,
    backgroundColor: '#f5f7fa',
  },
  pic: {
    marginBottom: 10,
    backgroundColor: '#fff',
    borderBottomWidth: 1 / PixelRatio.get(),
    borderBottomColor: '#e1e1e1'
  },
  img: {
    width: WIDTH,
    height: WIDTH,
  },
  detail: {
    paddingTop: 15,
    paddingLeft: 10,
    paddingRight: 10,
    marginBottom: 10,
    backgroundColor: '#fff',
    borderTopWidth: 1 / PixelRatio.get(),
    borderTopColor: '#e1e1e1',
    borderBottomWidth: 1 / PixelRatio.get(),
    borderBottomColor: '#e1e1e1'
  },
  detailMain: {
    paddingBottom: 13,
    borderBottomWidth: 1 / PixelRatio.get(),
    borderBottomColor: '#e1e1e1'
  },
  detailLast: {
    borderBottomWidth: 0,
    borderBottomColor: 'transparent',
  },
  grey: {
    fontSize: 14,
    color: '#bbc1c6'
  },
  proText: {
    paddingTop: 6,
    fontSize: 14,
    paddingBottom: 6,
    height: 48,
    lineHeight: 18,
    color: '#333'
  },
  priceText: {
    fontSize: 16,
    color: '#ff8a00'
  },
  sale: {
    flex: 1,
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    paddingTop: 15,
  },
  saleMain: {
    flex: 1,
    flexDirection: 'row',
    alignItems: 'center',
  },
  arrow: {
    width: 9,
    height: 5
  },
  text: { fontSize: 14, },
  labelText: {
    fontSize: 12,
    color: '#fff',
  },
  black: {
    marginLeft: 5,
    color: '#333',
  },
  pt: { paddingTop: 3,},
  label: {
    paddingTop: 3,
    paddingRight: 8,
    paddingBottom: 3,
    paddingLeft: 8,
    marginLeft: 10,
    borderRadius: 2,
    alignItems: 'center'
  },
  labelError: {
    backgroundColor: '#fb7574'
  },
  labelInfo: {
    backgroundColor: '#3fb7ea'
  },
  labelWarning: {
    backgroundColor: '#ffc617'
  },
  saleDetail: {
    paddingTop: 3,
    paddingLeft: 78,
  },
  infor: {
    paddingTop: 15,
    backgroundColor: '#fff',
    borderTopWidth: 1 / PixelRatio.get(),
    borderTopColor: '#e1e1e1',
  },
  tab: {
    paddingLeft: 32,
    paddingRight: 32,
  },
  tabBtn: {
    flex: 1,
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    borderWidth: 1 / PixelRatio.get(),
    borderColor: '#3d85cc',
    borderRadius: 3,
    overflow: 'hidden'
  },
  tabButton: {
    flex: 1,
    height: 40,
    alignItems: 'center',
    justifyContent: 'center',
  },
  tabButtonCur: { backgroundColor: '#3d85cc' },
  txt: {
    fontSize: 14,
    color: '#326da7'
  },
  txtCur: { color: '#fff' },
  cont: {
    flex: 1,
    paddingTop: 10,
    paddingBottom: 10,
    alignItems: 'center'
  },
  proImage: {
    width: WIDTH,
    height: WIDTH
  },
  property: {
    paddingTop: 20,
    paddingRight: 10,
    paddingBottom: 15,
    paddingLeft: 10,
  },
  propertyTitle: {
    marginBottom: 15,
    fontSize: 14,
    fontWeight: 'bold',
    color: '#333',
  },
  listRow: {
    flex: 1,
    flexDirection: 'row',
    marginBottom: 10
  },
  propertyName: {
    fontSize: 14,
    color: '#333',
    paddingRight: 10,
    width: 80,
  },
  propertyTxt: {
    flex: 1,
    flexWrap: 'wrap',
    fontSize: 14,
    color: '#939495'
  },
  back: {
    position: 'absolute',
    top: 20,
    left: 10,
    width: 32,
    height: 32,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: 'rgba(0,0,0,0.5)',
    borderRadius: 16,
  },
  backLeft: {
    width: 10,
    height: 19,
  },
  innerContainer: {
    flex: 1,
    backgroundColor: '#FFF',
    justifyContent: 'center'
  },
  bottom: {
    flexDirection: 'row',
    paddingLeft: 10,
    paddingBottom: 10,
  },
  btn: {
    alignItems: 'center',
    justifyContent: 'center',
    width: (WIDTH-10)/2-10,
    marginRight: 10,
    paddingTop: 13,
    paddingBottom: 13,
    backgroundColor: '#43c6a6',
  },
  mktRow: {
    flexDirection: 'row'
  },
  mktBody:{
    justifyContent: 'center',
    marginTop: 5,
    paddingLeft: 10,
    paddingRight: 10,
    height: 24,
  },
  gitsListView : {
    paddingRight: 10,
    paddingLeft: 10,
  },
  flexGrow: {
    flex: 1,
  },
  giftNameItem: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
  },
  detailOneLine: {
    flex: 1,
    flexDirection: 'row',
    justifyContent: 'flex-start',
    alignItems: 'center',
    height: 18,
    marginBottom: 6,
  },
  labelTxt: {
    fontSize: 12,
    color: '#fff',
    backgroundColor: 'transparent',
  },
  labelGift: {
    width: 40,
    height: 18,
    marginRight: 2,
    justifyContent: 'center',
    alignItems: 'center',
  },
  giftBg: {
    position: 'absolute',
    top: 0,
    left: 0,
    width: 40,
    height: 18,
  },
  giftTxt: {
    fontSize: 14,
    color: '#939495'
  },
});


module.exports = ProductDetail;
